package indi.service;

import java.io.*;
import java.util.*;

import indi.entity.Book;
import indi.entity.Title;
// 注意：可以不需要
// 为什么要继承，因为Title类是所有存储书籍的父类，所以对
// 继承自Title的Book，也要有TitleService中的方法。
public class BookService extends TitleService {
	
	//累计书本个数。可以不要
	static int COUNTOFBOOK;
	//当前系统中书本
	private ArrayList<Book> currentBooks;
	
	//文件位置
	private static final String filePosition = "data//book.txt";
	
	
	
	public BookService() {
		super();
		//this.COUNTOFBOOK = 0;
		this.currentBooks = new ArrayList<>();
		//this.filterBookFromTitle();
		this.COUNTOFBOOK = currentBooks.size();
	}
	

	// 过滤书籍中的书本类到当前类
	public boolean filterBookFromTitle(
			ArrayList<Title> titles){
		//ArrayList<Book> booksInTitle = new ArrayList<>();

		// 首先从数据库中读取所有的Title
		if(this.currentTitles == null) {
			//readTitlesFromDB();
			return true;
		}
		// 遍历，判断是否为Book实例
		for(Title t: this.currentTitles) {
			if(true == t) {
				currentBooks.add(((Book)t));
			}
		}
		return true;
	}
	
	public static void main(String[] args) {
		BookManager manager = new BookManager();
		ArrayList<Book> books = manager.getCurrentBooks();
		
		for(Book e:books) {
			//e.printBook();
			System.out.println(e);
		}
		
		System.out.println("添加后...\n");
		manager.addOneBook("《流浪地球》", "刘慈欣", "科幻", "555");
		manager.loadBook();
		books = manager.getCurrentBooks();
		for(Book e:books) {
			//e.printBook();
			System.out.println(e);
		}
	}
/*
	// 像当前列表中添加书籍
	public boolean addOneBook(String bookName, String author, 
			String type, String isbn, int totalNum, float price) {
		try {
		Book oneBook = new Book(isbn, author, totalNum, 
				bookName, price, type, this.MAINTAINDAYS);
		// 添加到当前书本列表
		currentBooks.add(oneBook);
		return true;
		}catch(Exception ex) {
			ex.printStackTrace();
		}
		return false;
	}
	
	
	//向文件中添加书本
	public boolean addOneBookToFile(String bookName, String author, 
			String type, String isbn, int totalNum, float price) {
		
		try {
			File file  = new File(filePosition);
			Title oneBook = new Title(isbn, author, totalNum, bookName, price, type);
			//books.add(oneBook);
			//无法读入情况
			if(null == file) {
				System.out.println("无法添加书本，文件位置出错！");
			}
			//向文件中添加书本
			try (
					MyObjectOutputStream output = new MyObjectOutputStream(
							new FileOutputStream(file, true));
			){
				//向列表中添加书本数据
				//currentBooks.add(oneBook);
				//向文件尾部添加书本数据
				output.writeObject(oneBook);
				output.flush();
			}catch(Exception e) {
				e.printStackTrace();
			}
			//书本计数器++
			this.COUNTOFBOOK++;
		}catch(Exception e) {
			throw e;
		}
		return true;
	}
	
	// 删除当前列表中的书本
		public boolean deleteOneBook(String isbn) {
			Book oneBook = this.queryBookByIsbn(isbn);
			
			if(oneBook == null) {
				return false;
			}
			else {
				currentBooks.remove(oneBook);
			}
			return true;
		}
	
	//从文件导入书本数据
	public boolean loadBook() {
		//根据位置获取文件类
		File file  = new File(this.filePosition);
		//删除掉books中数据，用于重新导入
		/*if(false == currentBooks.removeAll()) {//这里不能删Null，否则报错NullPoint...
			System.out.println("无法移除");
			return false;
		}/
		currentBooks.clear();
		
		//输入数据
		if(null == file) {
			System.out.println("无法输入书本！");
			return false;
		}
		try (
				ObjectInputStream input = new ObjectInputStream(
						new FileInputStream(file));
		){
			while(true) {
				Book oneBook = (Book)(input.readObject());
				if(null != oneBook) {
					currentBooks.add(oneBook);
				}else {
					break;
				}
			}
		}catch(EOFException e) {
		
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		return true;
	}
	
	//通过书名查询书本
	public ArrayList<Book> queryBookByBookName(String bookName) {
		
		ArrayList<Book> booksToQuery = new ArrayList<>();
		
		for(Book e: currentBooks) {
			if(true == e.getBookName().equals(bookName)) {
				booksToQuery.add(e);
			}
		}
		
		return booksToQuery;
	}
	
	//通过ISBN号查询图书
	public Book queryBookByIsbn(String isbn){
		//遍历查找
		for(Book e: currentBooks) {
			if(true == e.getISBN().equals(isbn)) {
				return e;
			}
		}
		
		return null;
	}
	
	//更新书本
	public boolean updateOneBook(Book book, String newAuthor, String newBookName, 
			String newType, String newIsbn) throws Exception{
		Book copyBook = null;
		try {
			//备份书本数据
			copyBook = new Book(book);
			//更新书本信息
			book.setAuthor(newAuthor);
			book.setBookName(newBookName);
			book.setType(newType);
			book.setISBN(newIsbn);
			book.setDays(this.MAINTAINDAYS);
			return true;
		}catch(Exception e) {
			book.setAll(copyBook);
			throw e;
		}
	}
	
	//判断书本是否在馆
	public boolean isInLibrary(Book book) {
		return (book.isOnLibrary());
	}
	
	//添加与书本与借书记录之间的关联,及对借阅书本后的关联处理
	public boolean addRelatedRecord(Book book, RecordOfBorrow newRecord) {
		book.setCurrentRecord(newRecord);
		book.setOnLibrary(false);
		book.setCountOfBorrowed(book.getCountOfBorrowed()+1);
		return true;
	}
	//取消书本与借阅记录之间的联系，及对借阅书本后的关联处理
	public boolean deRelatedRecord(Book book) {
		book.setCurrentRecord(null);
		book.setOnLibrary(true);
		return true;
	}
	 */
	public ArrayList<Book> getCurrentBooks() {
		return currentBooks;
	}


	
}

//定义自定义文件输出流，来实现向文件尾部添加数据
class MyObjectOutputStream extends ObjectOutputStream{
	
	public MyObjectOutputStream(OutputStream os) throws IOException{
		super(os);
	}
	
	@Override
	protected void writeStreamHeader() throws IOException{
		super.reset();
	}
}
//定义自定义文件输入流，来实现不读取头
class MyObjectInputStream extends ObjectInputStream{
	
	MyObjectInputStream(InputStream in) throws IOException{
		super(in);
	}
	
	@Override
	protected void readStreamHeader()
	        throws IOException, StreamCorruptedException{
		
	}
}

